<?php
/** ***********************
 * 作者：Zpy 
 * 日期：2016/11/29
 * 作用：发票视图模型
 ** ***********************/
class ticketViewHome extends coreFrameworkView
{
	public $ticket_class;//发票类
	public $ticket_info;//发票信息
	public $business;//商户信息
	public $post;//数据
	public $appkey;//应用key
	public $appkey_info;//应用信息
	public $timestamp;//时间戳
	public $sign;//签名
	public $type;//请求接口
	
	function __construct(){
		parent::__construct();
		
		//验证数据
		$this->checkOption();
		
		//引入发票类
		require( _SITE_INCLUDE_CLASS_PATH.'/fapiao.Class.php');
		//参数配置
		$config = array(
			//start 正式地址 gzy
			//'host' =>'api.fapiaoxx.com',
			//'port' =>'',
			//end
			//start 测试地址 gzy
			'host' =>'42.159.205.189',	
			'port' =>'8301',
			//end
			'taxpayerId' =>$this->business['taxpayerId'],
			'taxpayerKey' =>$this->business['taxpayerKey'],
			'buiness_name'=>$this->business['business_name'],
		);
		
		//实例化发票类
		$this->ticket_class = new fapiao($config);
		
		
	}
	//验证数据
	function checkOption(){
		//验证是否有数据
		$post = file_get_contents('php://input');
		if (!$post){
			$this->returnJson('',2001);
			die;
		}
		$this->post = json_decode($post,true);
		//验证是否有时间戳
		$this->timestamp = $this->GVar->fget['timestamp'];
		
		if (!$this->timestamp){
			$this->returnJson('',2007);
			die;
		}
		//验证是否有appkey
		$this->appkey = $this->post['appkey'];
		
		if (!$this->appkey){
			$this->returnJson('',2008);
			die;
		}
		
		//验证是否有sign
		$this->sign=$this->GVar->fget['sign'];
		
		if (!$this->sign){
			$this->returnJson('',2009);
			die;
		}
		
		
		
		/*if (!$this->post['number']) {
			
			$this->returnJson('',2010);
			die;

		}*/
		
		
		
		if (!$this->post['businesskey']) {
			
			$this->returnJson('',2013);
			die;

		}
		//验签 start
		$this->sign_check($this->post,$this->timestamp,$this->sign);
		
		//$this->ticket_info = $this->model->getTicketInfo($this->post['number']);
		
		$this->type = $this->GVar->fget['t'];
		
	}
	//验签下游sign
	function sign_check($data,$timestamp,$sign){
		ksort($data);
		$appkey = $data['appkey'];
		unset($data['appkey']);
		$businesskey = $data['businesskey'];
		unset($data['businesskey']);
		$str = '';
		foreach($data as $key=>$value)
		{
			if ($value){
				$str .= $key.'='.$value;
			}
			
		}
		$encry_sign=MD5($str.'timestamp='.$timestamp.'businesskey='.$businesskey.'appkey='.$appkey);
		
		if($encry_sign==$sign)
		{
			//获取应用信息
			$app_info = $this->model->getAppKeyInfo($appkey);
			
			if (!$app_info){
				$this->returnJson('',2005);
				die;
			}
			//获取商户信息
			$business_info = $this->model->getBusinessInfo($businesskey);
			
			if (!$business_info){
				$this->returnJson('',2014);
				die;
			}
			
			$this->appkey_info = $app_info;
			$this->business = $business_info;
			
			//验证appkey权限
			$this->checkAppkeyAuth();
			
			
		}else{
			$this->returnJson('',2004);
			die;
		}
		
		
		
	}
	//验证appkey权限
	function checkAppkeyAuth($number){
		$shop_ids = explode(',',$this->appkey_info['author_business_id']);
		if(!in_array($this->business['id'],$shop_ids)){
			$this->returnJson('',2006);
			die;
		}else{
			
			
		}
		
	}
	//预下单
	function createTicket(){
		//$res = $this->model->createTicket($this->post,$this->business);
		$post = $this->post;
		foreach ($post['count'] as $k=>$v){
			$price += $v*$post['unitPrice'][$k];
		}
		
		$number = date('YmdHis').rand(1000,9999);
		$data = array(
			'price'=>$price,
			'shop_id'=>$post['shop_id'],
			'c_time'=>time(),
			'number'=>$number,
			'create_user'=>$this->GVar->session['user_root']['id'],
			'status'=>1,
		);
		$res = $this->model->createTicket($data);
		if ($res) {
			foreach ($post['wareName'] as $k=>$v){
				$insert_data[] = array(
					'wareName'=>$v,
					'count'=>$post['count'][$k],
					'unit'=>$post['unit'][$k],
					'unitPrice'=>$post['unitPrice'][$k],
					'taxRate'=>$post['taxRate'][$k],
					'ticket_id'=>$res,
					'c_time'=>time(),
				
				);
			}
			$res = $this->model->insertTicketGoods($insert_data);
			$return_data = array(
				'number'=>$number
			
			);
			$this->returnJson($return_data);
		}else{
			$this->returnJson('',2014);
		}
	}
	
	//开票
	function openTicket(){
		//开票
		$this->ticket_info = $this->model->getTicketInfo($this->post['number']);
		$item = $this->model->getTicketGoods($this->ticket_info['id']);

		foreach ($item as $k=>$v){
			unset($item[$k]['ticket_id']);
		}
		$this->post['wareListInfo'] = $item;
		$res = $this->ticket_class->openTicket($this->post);
		if($res['code']=='0000'){
			$data = array(
				'requestCode'=>$res['requestCode'],
				'status'=>2,
				'open_time'=>time(),
			
			);
			$this->model->updateTicket($this->post['orderNo'],$data);
			
			$return_data = array(
				'requestCode'=>$res['requestCode'],
				'number'=>$this->post['number'],
				'price'=>$this->ticket_info['price'],
			
			);
			$this->returnJson($return_data,200);
			
		}elseif($res['code']=='9141'){			
			$this->returnJson($res,2015);
		}else{			
			$this->returnJson('',$res,$res['resMsg']);
		}
	}
	
	//获取发票信息
	function getTicketInfo(){
		
		if (!$this->post['number']){
			$this->returnJson('',2001);
			die;
		}
		
		
		$ticketinfo = $this->model->getTicketInfo($this->post['number']);
		
		if ($ticketinfo) {
			$goods = $this->model->getTicketGoods($ticketinfo['id']);
			
			$return_data = array(
				'price'=>$ticketinfo['price'],
				'create_time'=>$ticketinfo['c_time'],
				'number'=>$ticketinfo['number'],
				'business_name'=>$ticketinfo['business_name'],
				'goods'=>$goods
			);
			
			//待开票
			if ($ticketinfo['status']==1) {
				$this->returnJson($return_data);
			//已经开票
			}elseif ($ticketinfo['status']==2){
				if ($ticketinfo['is_save']) {
					
				}else{
					//$ticketinfo['content'] = $this->queryTicket($ticketinfo['requestCode']);
					
					$this->returnJson($return_data);
					
				}
				$this->returnJson($return_data);
			}
		}else{
			$this->returnJson('',2002);
			die;
		}
		
		
		
	}
	//查询发票
	function queryTicket($requestCode){
		
		//查询原发票信息
		$this->ticket_info = $this->model->getTicketInfo($this->post['number']);
		//print_r($this->ticket_info);
		//如果发票的查询状态为1 则标识已经开具成功 则从数据库中查询 不调用接口
		if($this->ticket_info['query_status']==1){
			
			//发票查询信息
			$query_data = $this->model->getTicketQuery($this->post['requestCode']);
			
			
			//发票图片
			$images = $this->model->getTicketQueryImages($query_data['id']);
			
			
			foreach ($images as $v){
				$img[] = $v['true_imageFiles'];
			}
			//返回信息
			$return = array(
			
				'code'=>$query_data['code'],//发票状态
				'invoiceCode'=>$query_data['invoiceCode'],//发票代码
				'invoiceNo'=>$query_data['invoiceNo'],//发票号码
				'open_time'=>$this->ticket_info['open_time'],//开票时间
				'business_name'=>$this->ticket_info['business_name'],//商户名称
				'pdfFile'=>$query_data['true_pdfFile'],//pdf下载地址
				'images'=>$img,//图片地址
			
			);
			
			$this->returnJson($return);
			die;
			
		}
		//发票查询接口
		$data = array(
			'requestCode'=>$this->post['requestCode']
		);
		$resault = $this->ticket_class->query($data);


		if (in_array($resault['code'],array('0000','1111','2222'))){
			$query_data = $resault;
			
			switch ($query_data['code']){
				case '0000':
				  $update_data['query_status']=1;
				  break;
				case '1111':
				  $update_data['query_status']=2;
				  break;
				case '2222':
				  $update_data['query_status']=3;
				  break;
				default:
				  $update_data['query_status']=2;
			}
			
			
			//如果状态发生改变 则更新发票状态信息
			if ($update_data['query_status'] != $this->ticket_info['query_status']){
				$where[] = 'requestCode="'.$this->post['requestCode'].'"';
				$this->model->updataTicket($update_data,$where);
			}
			
			//如果状态发生改变并开具成功 则更新查询状态信息
			if($query_data['code']=='0000' && $update_data['query_status'] != $this->ticket_info['query_status']){
				unset($query_data['items']);
				//图片地址
				$images = $query_data['imageFiles'];
				unset($query_data['imageFiles']);
				$query_data['issueDate'] = strtotime($query_data['issueDate']);
				$query_data['c_time'] = time();
				$query_data['true_pdfFile'] = $query_data['pdfFile'];
				
				$query_id = $this->model->saveTicketQuery($query_data);
				if ($query_id) {
					foreach ($images as $v){
						$insert_data[] = array(
							'q_id'=>$query_id,
							'imageFiles'=>$v,
							'true_imageFiles'=>$v,
							'c_time'=>time(),
						);
						$img[] = $v;
					}
					$this->model->saveTicketQueryImages($insert_data,$query_id);
				}
				
			}
			//返回信息
			$return = array(
				'code'=>$query_data['code'],//发票状态
				'invoiceCode'=>$query_data['invoiceCode'],//发票代码
				'invoiceNo'=>$query_data['invoiceNo'],//发票号码
				'pdfFile'=>$query_data['true_pdfFile'],//pdf下载地址
				'images'=>$img,//图片地址
			
			);
			
			$this->returnJson($return);
		}else{
			//查询失败
			$this->returnJson('',2012);
		}
	
	
	}
	//冲红
	function revoke(){
		
		$data = array(
			'orderNo'=>$this->post['number'],
			'replacedInvoiceCode'=>$this->post['replacedInvoiceCode'],//原发票代码
			'replacedInvoiceNo'=>$this->post['replacedInvoiceNo'],//原发票号码
			'requestCode'=>$this->post['revokeReson'],//冲红原因
		);
		
		$resault = $this->ticket_class->revoke($data);
		
		if ($resault) {
			$this->returnJson($resault);
		}else{
			$this->returnJson('',2011);
		}
		
		
	}
	
	//开票统计
	function querybillingcount(){
		
		$data = array(
			'queryDate'=> $this->post['queryDate'],//YYYYMM 统计月份
		);
		
		$resault = $this->ticket_class->querybillingcount($data);
		
		
		if ($resault) {
			$this->returnJson($resault);
		}else{
			$this->returnJson('',2012);
		}
		
		
	}
	//余票查询
	function queryBillLeftCount(){
		
		$resault = $this->ticket_class->queryBillLeftCount();
		
		if ($resault) {
			$this->returnJson($resault);
		}else{
			$this->returnJson('',2012);
		}
		
		
	}
	//api返回数据处理
	function returnJson($data='',$error_code=200,$msg){
		$send_data = array(
			'error_code'=>$error_code,
			'data'=>$data,
			'error_msg'=>($msg)?$msg:$this->errorCodeData($error_code)
		);
		
//		echo json_encode($data,JSON_UNESCAPED_UNICODE);
//		$send_data = json_encode($data);
//		插入日志
		$this->insertApiLog($send_data);
		echo json_encode($send_data);
	}
	//错误代码
	function errorCodeData($error_code){
		$error_msg = array(
			'200'=>'ok',
			'2001'=>'缺少必要参数',
			'2002'=>'参数发票信息失败',
			'2003'=>'开票失败',
			'2004'=>'签名不正确',
			'2005'=>'appkey不正确',
			'2005'=>'appkey不正确',
			'2006'=>'appkey没有操作该商户权限',
			'2007'=>'缺少timestamp',
			'2008'=>'缺少appkey',
			'2009'=>'缺少sign',
			'2010'=>'缺少number',
			'2011'=>'冲红失败',
			'2012'=>'查询失败',
			'2013'=>'缺少businesskey',
			'2014'=>'预下单失败',
			'2015'=>'订单号已经开票成功或者已受理',

		);
		
		return $error_msg[$error_code];
	}
	//插入log
	function insertApiLog($send_data){
		
		$insert_data = array(
			'channel_id'=>$this->appkey_info['channel_id'],  //渠道ID
			'app_id'=>$this->appkey_info['id'],	//应用id
			'type'=>$this->type,  //类型
			'receive_data'=>json_encode($this->post),//报文
			'sign'=>$this->sign,// 签名
			'appkey'=>$this->appkey,// appkey
			'send_data'=>json_encode($send_data),// 返回内容
			'api_url'=>$this->curPageURL(),// 接口地址
			'timestamp'=>$this->timestamp,// 时间
			'error_code'=>$send_data['error_code'],// 状态码
		);
		
		$this->model->insertApiLog($insert_data);
		
	}
	function curPageURL(){
	  $pageURL = 'http';
	
	  if ($_SERVER["HTTPS"] == "on"){
	    $pageURL .= "s";
	  }
	  $pageURL .= "://";
	
	  if ($_SERVER["SERVER_PORT"] != "80"){
	    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
	  } else{
	    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
	  }
	  return $pageURL;
	}


}

?>